package com.xrui.hbase.compression;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Implements a CompressionProvider with Gzip.
 */
public class GzipCompressionProvider implements CompressionProvider {
    public static final String PROVIDER_NAME = "gzip";

    /**
     * {@inheritDoc}
     */
    @Override
    public byte[] compress(byte[] data) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        GZIPOutputStream out = new GZIPOutputStream(bytes);
        out.write(data);
        out.finish();
        return bytes.toByteArray();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public byte[] decompress(byte[] compressedData) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream(compressedData.length);
        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressedData));
        byte[] buffer = new byte[compressedData.length];
        for (; ; ) {
            int bytesRead = in.read(buffer, 0, buffer.length);
            if (bytesRead < 0) {
                break;
            }
            bytes.write(buffer, 0, bytesRead);
        }
        return bytes.toByteArray();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return PROVIDER_NAME;
    }
}
